import fs from 'fs'
import path from 'path'
import { Message, Middleware } from 'mirai-js'
import { MessageType } from 'mirai-js/dist/node/BaseType'
import mcping from 'mcping-js'
import appConfig from '../config/app.config'
/**
 *
 * @param {*} all
 * @returns 类型String
 */
const Typeing = (item: any): string => {
  return Object.prototype.toString.call(item).slice(8, -1).toLowerCase()
}
const commondTextFilter = (value: string): string => {
  let str: string[] = value.split(' ')
  if (str.length >= 2) {
    return str[0]
  } else {
    return 'default'
  }
}
export interface McSever {
  favicon: string
  description: {
    text: string
  }
  players: { online: number; sample: any[] }
  version: { name: string }
}
type hasMcResReturn = {
  serviceOptenTime: string
  favicon: string
  name: string
  online: number
  sample: string
  version: string
}

const hasSample = (sample: any[]) => {
  if (Typeing(sample) != 'array') return
  let str = ''
  sample.map((item) => {
    str += `${item.name}\n`
  })
  return str
}
const hasMcResMessage = (res: McSever): hasMcResReturn => {
  const mcInfo: hasMcResReturn = {} as hasMcResReturn
  res.favicon && Object.assign(mcInfo, { favicon: res.favicon })
  res.description.text
    ? Object.assign(mcInfo, { name: res.description.text })
    : Object.assign(mcInfo, { name: 'A Minecraft Server' })
  Object.assign(mcInfo, { online: res.players.online || 0 })
  res.players.sample && Object.assign(mcInfo, { sample: hasSample(res.players.sample) })
  res.version.name && Object.assign(mcInfo, { version: res.version.name })
  const imgData = res.favicon
  if (imgData) {
    var base64Data = imgData.split(',')
    var dataBuffer = Buffer.from(base64Data[1], 'base64')
    fs.writeFile(path.join(__dirname, 'image.png'), dataBuffer, function (err) {
      if (err) {
        return
      }
    })
  }

  return mcInfo
}

class mcMessage extends Message {
  constructor(res: hasMcResReturn) {
    super()
    this.addImagePath(
      res.favicon ? path.join(__dirname, 'image.png') : path.join(__dirname, '../../public/mc_server_icon.png'),
    )
    const openServerTimeStr = () => {
      if (!res.serviceOptenTime) return null
      const time = (new Date().getTime() - new Date(res.serviceOptenTime).getTime()) / (1000 * 60 * 60 * 24)
      return '\n已开服' + parseInt(time+'') + '天'
    }

    const resServerTime = openServerTimeStr()
    this.addText(
      `${res.name}\n版本:${res.version}\n当前在线: ${res.online}人${resServerTime ? resServerTime : ''}${
        res.sample ? '\n附属信息:' : ''
      }${res.sample || ''}`,
    )
  }
}
const mcpingServer = (ip: string, port: number): Promise<McSever> => {
  const server = new mcping.MinecraftServer(ip, port)
  return new Promise((resolve, reject) => {
    server.ping(appConfig.TIMEOUT_TIME, 760, (err, res) => {
      if (err) {
        reject(err)
      }
      resolve(res)
    })
  })
}
export { Typeing, commondTextFilter, hasMcResMessage, mcpingServer, mcMessage }
